package com.chatplus.application.datasource.fill;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.chatplus.application.datasource.id.IdEntity;
import org.apache.ibatis.reflection.MetaObject;

import java.time.Instant;

/**
 * 自定义元数据处理具柄实现，用于新增和更新的时候，对创建时间和更新时间维护
 */
public class CustomMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        if (!IdEntity.class.isAssignableFrom(metaObject.getOriginalObject().getClass())) {
            return;
        }
        Instant instant = Instant.now();
        this.fillStrategy(metaObject, IdEntity.CREATED_AT_FIELD_NAME, instant);
        this.fillStrategy(metaObject, IdEntity.UPDATED_AT_FIELD_NAME, instant);
    }

    @Override
    public void updateFill(MetaObject metaObject) {

        if (!IdEntity.class.isAssignableFrom(metaObject.getOriginalObject().getClass())) {
            return;
        }
        Instant instant = Instant.now();
        setFieldValByName(IdEntity.UPDATED_AT_FIELD_NAME, instant, metaObject);
    }
}
